const superagent = require("../config/index");
const Superagent = require("superagent");
const cheerio = require("cheerio");
const fs = require("fs");
const nodeSchedule = require("node-schedule");
// const request = require("request");
const ONE = "http://wufazhuce.com/"; // ONE的web版网站
const POISON = "https://8zt.cc/api/"; //毒鸡汤网站
const weiboURL = "https://s.weibo.com";
const hotSearchURL = weiboURL + "/top/summary?cate=realtimehot";
const hotSearchCookies = `_s_tentry=passport.weibo.com; Apache=4950475133032.61.1638282900861; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WWoggCvDOxY-vXVGiYzJfVc; ULV=1638283021540:1:1:1:4950475133032.61.1638282900861:; SINAGLOBAL=4950475133032.61.1638282900861; SUB=_2AkMW-rguf8NxqwJRmfoWy2_lb4V0yQvEieKgpkn1JRMxHRl-yj9jqkEstRB6PXqWwYYhR1PFXzQX0RwK4Xny_dUzd9p3`;
/**
 * 获取热搜列表数据方法
 */
function getHotSearchList() {
  return new Promise((resolve, reject) => {
    Superagent.get(hotSearchURL)
      .set("cookie", hotSearchCookies)
      .end((err, res) => {
        if (err) reject("request error");
        const $ = cheerio.load(res.text);
        let hotList = [];
        $("#pl_top_realtimehot table tbody tr").each(function (index) {
          if (index !== 0) {
            const $td = $(this).children().eq(1);
            const link = weiboURL + $td.find("a").attr("href");
            const text = $td.find("a").text();
            const hotValue = $td.find("span").text();
            const icon = $td.find("img").attr("src")
              ? "https:" + $td.find("img").attr("src")
              : "";
            hotList.push({
              index,
              link,
              text,
              hotValue,
              icon,
            });
          }
        });
        hotList.length ? resolve(hotList) : reject("errer");
      });
  });
}

/*
 * schedule
*    *    *    *    *    *    
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
 */
/**
 * 定时执行任务函数
 */
function asyncTask(cron, asynFun) {
  nodeSchedule.scheduleJob(cron, async function (asynFun) {
    try {
      console.log(typeof asynFun === "function");
      if (typeof asynFun === "function") {
        const hotList = await asynFun();
        await fs.writeFileSync(
          `${__dirname}/hotSearch.json`,
          JSON.stringify(hotList),
          "utf-8"
        );
        console.log("写入成功");
      } else {
        throw new Error("请传入执行定时任务的异步函数");
      }
    } catch (error) {
      console.error(error);
    }
  });
}

/**
 * 获取每日一句
 */
async function getOne() {
  try {
    let res = await superagent.req(ONE, "GET");
    let $ = cheerio.load(res.text);
    let todayOneList = $("#carousel-one .carousel-inner .item");
    let todayOne = $(todayOneList)
      .find(".fp-one-cita")
      .text()
      .replace(/(^\s*)|(\s*$)/g, "")
      .split("\n");

    return todayOne;
  } catch (err) {
    console.log("错误", err);
    return err;
  }
}

/**
 * 获取每日毒鸡汤
 */
async function getSoup() {
  try {
    let res = await superagent.req(POISON, "GET");
    // let $ = cheerio.load(res.text);
    // const content = $("#sentence").text();
    return JSON.parse(res.text);
  } catch (err) {
    console.error("err");
    return err;
  }
}

module.exports = {
  getOne,
  getSoup,
  asyncTask,
  getHotSearchList,
};
